<?
/*! \brief Represents a service within OpenBT 
 * 
 */
class Service extends XML
{
	protected $_serviceName, $_cmdBuilder, $_exit, $_output;
	
	function __construct($serviceName='') 
	{
		$this->_serviceName = $serviceName;
		$this->loadServiceXml();
	}
	
	public function loadServiceXml()
	{
		$fname = ServiceManager::getServiceDir().$this->getServiceName().'.xml';
		$this->setFileXml($fname);
	}
	
	public function getServiceName()
	{
		return $this->_serviceName;
	}
	
	public static function exists($serviceName='')
	{
		return file_exists(ServiceManager::getServiceDir().$serviceName.'.xml');
	}
	
	public function makeCommand()
	{
		$this->_cmdBuilder = new CommandBuilder($this);
	}
	
	public function getCommand()
	{
		return trim($this->_cmdBuilder->getCommand());
	}
	
	public function executeCommand()
	{
		//Get and execute the command
		$this->makeCommand();
		$str = $this->getCommand();
		set_time_limit(180);
		exec($str, $output, $this->_exit);
		$this->_output = implode("\n", $output);
		
		//Log the command being run and its output
		Logger::file()->info('Command: '.$str);
		Logger::file()->info('Exit Code: '.trim($this->_exit));

		if($output != null)
			Logger::file()->info('Output: '.trim($this->_output));
		
		//*NIX Specific
		if('directory' == $this->getSimple()->output->type || 
			'prefix' == $this->getSimple()->output->type)
		{
			$output = array();	
			exec('zip -rj ' . $this->_cmdBuilder->getFullFile() . ' ' .
				$this->_cmdBuilder->getDir('output') . ' 2>&1', $output, $this->_exit);
			
			if($this->_exit > 0)
			{
				Logger::file()->info('Zipping output failed.');
				$this->_output .= "\n";
				$this->_output .= implode("\n", $output);
			}
		}

		return $this->_cmdBuilder->getFullFile();
	}

	public function getRootDir()
	{
		return $this->_cmdBuilder->getDir('root');
	}
	
	public function getOutputDir()
	{
		return $this->_cmdBuilder->getDir('output');
	}
	
	public function getOutputFile()
	{
		return $this->_cmdBuilder->getOutputFile();
	}
	
	public function getFullFile()
	{
		return $this->_cmdBuilder->getFullFile();
	}
	
	public function getExitCode()
	{
		return $this->_exit;
	}
	
	public function getCmdOutput()
	{
		return $this->_output;
	}
	
	public function getErrorAsXML()
	{
		$xml =	'<?xml version="1.0" encoding="ISO-8859-1"?>'.
				'<openbt>'.
					'<error/>'.
					'<command><![CDATA['.$this->getCommand().']]></command>'.
					'<code>'.$this->_exit.'</code>'.
					'<output><![CDATA[' . $this->_output . ']]></output>'.
				'</openbt>';
		echo $xml;
		return $xml;
	}
}
